<template>
    <!-- 纯公式展示 -->
    <div class="formula-editor">
        <div class="editor-container">
        <div class="content-box" v-if="codeModel === 1">
            <div v-for="item in functionContents" :key="item.id" class="draggable-navbar" :style="{ transform: `translate(${item.offsetX}px, ${item.offsetY}px)` }">
                <div :class="['content-item', 'content-item-factor']" v-if="item.type === 'factor'">{{ item.name }}</div>
                <div :class="['content-item', 'content-item-operator']" v-if="item.type === 'operator'">{{ item.name }}</div>
                <input :class="['content-item', 'content-item-number']" v-if="item.type === 'number'" 
                    :data-id="item.id" v-model="item.name" :size="Math.max(item.name.length - 1, 1)" readonly></input>
            </div>
        </div>
        </div>
    </div>
</template>

<script setup lang="ts">

// 接收父组件传入的公式信息
const props = defineProps({
    formula: String, 
    operators: {
        type: Array,
        default: () => [
            { name: '+', fontSize: '24', height: '24', fontWeight: 500 },
            { name: '-', fontSize: '24', height: '24', fontWeight: 500 },
            { name: '*', fontSize: '20', height: '16', fontWeight: 500 },
            { name: '/', fontSize: '18', height: '18', fontWeight: 600 },
            { name: '(', fontSize: '18', height: '18', fontWeight: 600 },
            { name: ')', fontSize: '18', height: '18', fontWeight: 600 }
        ]
    }
});

const codeModel = ref(1); // 固定为组件模式
const formula = ref('');

const functionContents = ref<any[]>([]);

// 将字符串解析为公式对象数组
function stringToItems(str: string): any[] {
    const items = [];
    let rowId = 1;
    let i = 0;

    while (i < str.length) {
        const char = str[i];

        if (char === '{') {
            const endIndex = str.indexOf('}', i);
            if (endIndex === -1) throw new Error('Unclosed factor bracket');
            const factorName = str.substring(i + 1, endIndex);
            items.push({ id: `factor-${rowId++}`, name: factorName, type: 'factor' });
            i = endIndex + 1;
        } else if (isDigit(char) || (char === '-' && isNextCharDigit(str, i))) {
            let numStr = char;
            i++;
            while (i < str.length && (isDigit(str[i]) || str[i] === '.')) {
                numStr += str[i];
                i++;
            }
            items.push({ id: `number-${rowId++}`, name: numStr, type: 'number' });
        } else if (isOperator(char)) {
            items.push({ id: `operator-${rowId++}`, name: char, type: 'operator' });
            i++;
        } else if (char === ' ') {
            i++;
        } else {
            throw new Error(`Unexpected character: ${char} at position ${i}`);
        }
    }
    return items;
}
const getFormula = (newValue: any) => {
    codeModel.value = 1;
    try {
        functionContents.value = stringToItems(newValue || '');
    } catch (error) {
        console.error('公式解析失败:', error);
        // 提供默认值或清空内容
        functionContents.value = [];
        // ElMessage.error('公式包含非法字符，请检查后重试');
    }
}
// 辅助函数
function isDigit(char: string) { return /[0-9]/.test(char); }
function isOperator(char: string) { return /[+\-*/()]/.test(char); }
function isNextCharDigit(str: string | any[], index: number) { return index + 1 < str.length && isDigit(str[index + 1]); }

// 初始化公式数据
const doInfo = () => {
    // console.log('公式：', props.formula);
    formula.value = props.formula?props.formula:'';
    getFormula(formula.value);
};

watch(() => props.formula, () => {
    doInfo();
}, { immediate: true });

onMounted(() => {
    doInfo();
});
</script>
<style lang="scss" scoped>
.formula-editor {
    color: var(--el-text-color-primary);
}

.content-box {
    min-height: 100px;
    padding: 10px;
    position: relative;
    display: flex;
    flex-wrap: wrap;
    cursor: col-resize;
}
.content-item {
    display: inline-flex;
    align-items: center;
    height: 30px;
    border-radius: 5px;
}

.content-item-factor {
    padding: 10px;
    background-color: var(--el-color-primary-light-9);
    font-size: 12px;
    border: 1px solid var(--el-color-primary-light-8);
}

.content-item-operator {
    padding: 10px 5px;
    font-family: cursive;
    background-color: transparent;
    border: 1px dashed transparent;
}

.content-item-number {
    padding: 10px 8px;
    border: 1px dashed var(--el-border-color-light);
    min-width: 28px;
    user-select: none;
    -webkit-user-select: none;
    font-family: monospace;
    /* 使用等宽字体 */
    font-size: 14px;
    cursor: auto;
}

.draggable-navbar {
    margin: 0 10px 10px 0;
    height: 30px;
    border-radius: 4px;
    overflow: hidden;
    cursor: auto;
    // transition: transform 0.1s ease;
    user-select: none;

    &.is-dragging {
        cursor: move;
        opacity: 0.7;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
}
</style>
